package com.co.recommend.service.impl;

import com.co.recommend.dao.DetailMapper;
import com.co.recommend.dao.SubMapper;
import com.co.recommend.dao.VideoMapper;
import com.co.recommend.dao.VideoStateMapper;
import com.co.recommend.pojo.Sub;
import com.co.recommend.service.SubService;
import com.co.video.dto.VideoDto;
import com.co.video.pojo.Detail;
import com.co.video.pojo.Video;
import com.co.video.pojo.VideoState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service
public class SubServiceImpl implements SubService {

    private static final Logger log = LoggerFactory.getLogger(SubServiceImpl.class);

    @Autowired
    private SubMapper subMapper;

    @Autowired
    private DetailMapper detailMapper;
    @Autowired
    private VideoStateMapper videoStateMapper;
    @Autowired
    private VideoMapper videoMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    /**
     * 添加订阅up主
     *
     * @param userName 用户名
     * @param upName   UP主
     * @return
     */
    @Override
    public boolean addSub(String userName, String upName) {
        Sub sub = new Sub();
        sub.setSubName(userName);
        sub.setPubName(upName);
        Sub subInfo = subMapper.selectOne(sub);

        if (subInfo == null) {//没有订阅过
            //添加订阅
            subMapper.insertSelective(sub);
            log.info(userName + "成功订阅" + upName);
            return true;

        }
        log.info(userName + "已经订阅了" + upName);
        return false;
    }

    /**
     * 删除订阅
     *
     * @param userName
     * @param upName
     * @return
     */
    @Override
    public boolean removeSub(String userName, String upName) {
        Sub sub = new Sub();
        sub.setSubName(userName);
        sub.setPubName(upName);
        Sub subInfo = subMapper.selectOne(sub);
        if (subInfo != null) {//
            //添加订阅
            subMapper.delete(sub);
            log.info(userName + "成功取消订阅" + upName);
            return true;

        }

        log.info(userName + "还没有订阅" + upName);
        return false;
    }

    /**
     * 更新推送
     *
     * @param aid
     */
    @Override
    public void push(String upName, String aid) {
        Sub sub = new Sub();
        sub.setPubName(upName);
        List<Sub> subs = subMapper.select(sub);
        if (subs == null || subs.size() <= 0) {
            //还没有人订阅
            log.info("没有人订阅你，不用推送");
            return;
        }
        //订阅的用户
        Map<String, Object> map = new HashMap<>();
        ArrayList<String> subNames = new ArrayList<>();
        for (Sub sub1 : subs) {
            subNames.add(sub1.getSubName());
        }

        map.put("upName", upName);
        map.put("subNames", subNames.toArray());
        //根据视频状态信息aid查询视频总信息
        Detail detail = detailMapper.selectByPrimaryKey(aid);

        //根据aid查询子视频
        Video video = new Video();
        video.setAid(aid);
        List<Video> videos = videoMapper.select(video);

        //根据Aid查询状态
        VideoState videoState = new VideoState();
        videoState.setAid(aid);
        VideoState videoState1 = videoStateMapper.selectOne(videoState);

        //封装视频对象
        VideoDto videoDto = new VideoDto();
        videoDto.setDetail(detail);
        videoDto.setVideos(videos);
        videoDto.setVideoState(videoState1);

        map.put("videoDto", videoDto);
        //存入redis  //设置超时时间72小时 第三个参数控制时间单位，详情查看TimeUnit
        redisTemplate.boundValueOps("pub_" + upName + "_" + aid).set(map, 72, TimeUnit.HOURS);

        if (redisTemplate.opsForValue().get("new_pub_" + upName + "_" + detail.getUploadTime().getTime()) == null) {
            Queue<Object> queue = new LinkedList<Object>();
            queue.add(map);
            redisTemplate.boundValueOps("new_pub_" + upName + "_" + detail.getUploadTime().getTime()).set(queue);
            return;
        }
        Queue<Object> new_pub = (Queue<Object>) redisTemplate.opsForValue().get("new_pub_" + upName + "_" + detail.getUploadTime().getTime());
        if (new_pub.size() < 1) {
            new_pub.add(map);
        } else {
            new_pub.remove();
            new_pub.add(map);
        }
        redisTemplate.boundValueOps("new_pub_" + upName + "_" + detail.getUploadTime().getTime()).set(new_pub);
        log.info("推送视频完成");
    }

    //订阅
    @Override
    public List<Object> subVideo(String userName) {

        List<Object> list = new ArrayList<>();
        List<String> upNames = subMapper.findPubName(userName);
        if (upNames == null || upNames.size() <= 0) {
            //还没有人订阅
            log.info("你没有订阅");
            return null;
        }
        for (String upName : upNames) {
            // 获取upName对应的所有的key
            Set<String> keys = redisTemplate.keys("pub_" + upName + "_*");
            //批量获取值
            List<Object> values = redisTemplate.opsForValue().multiGet(keys);
            list.add(values);
        }


        return list;
    }

    //订阅
    @Override
    public Object subVideo(String userName, String aid) {

        if("_all".equals(aid)){
            List<Object> listValue = new ArrayList<>();
            //aid == all， 就获取最新的4个视频

            List<String> upNames = subMapper.findPubName(userName);

            Map<Long,Object> map = new HashMap<>();
            for (String upName : upNames) {
                // 获取upName对应的所有的key
                Set<String> keys = redisTemplate.keys("new_pub_" + upName + "_*");

                //给key值排个序
                if (keys == null) {
                    log.info("当前没有最新视频");
                    return null;
                }
                //批量获取值
                List<Object> values = redisTemplate.opsForValue().multiGet(keys);

                if(values !=null&&values.size()>0){
                    //listValue.addAll(values);
                    String[] s = new ArrayList<String>(keys).get(0).split("_");
                    Long key = Long.parseLong(s[s.length-1]);

                    map.put(key,values.get(0));
                }
            }
            //只取4个
            List<Long> collect1 = new ArrayList<Long>(map.keySet()).stream().sorted().collect(Collectors.toList());
            Collections.reverse(collect1);
            int len = collect1.size() >= 4 ? 4 : collect1.size();
            for (int i = 0; i < len; i++) {
                listValue.add(map.get(collect1.get(i)));
            }
            return listValue;
        }

        //更具upName和aid得到订阅
        Detail detail = detailMapper.selectByPrimaryKey(aid);
        if (detail == null) {
            log.info("订阅的视频已删除....");
            return null;
        }
        String upName = detail.getUsername();
        Object values = redisTemplate.opsForValue().get("pub_" + upName + "_" + aid);

        return values;
    }
    //up主被多少人人订阅
    public Integer subCount(String upName){
        List<String> subNames = subMapper.findSubName(upName);
        return subNames.size();
    }
}
